<!--自定义滑块-->
<template>
  <div class="scroll" id="scroll">
    <div class="bar" id="bar"></div>
  </div>
</template>
<script>
export default {
  name: 'CustomSlider',
  data(){
    return{
      caption:"AAA",
    }
  },
  mounted() {
    const _this = this;
    //获取元素
    let scroll = document.getElementById("scroll");
    let bar = document.getElementById("bar");
    let ptxt = document.getElementsByTagName('p')[0];
    //添加事件
    bar.onmousedown = function(event) {
      event = event || window.event;
      //页面事件的Y减去当前相对于最近的祖先定位元素
      let y = event.clientY - this.offsetTop;
      // 拖动需要写到down里面
      document.onmousemove = function(event) {
        event = event || window.event;
        //获取移动的距离
        let top = event.clientY - y;
        if (top < 0){
          top = 0;
        }
        else if (top > scroll.offsetHeight - bar.offsetHeight){
          top = scroll.offsetHeight - bar.offsetHeight;
        }
        //改变滑块的top
        bar.style.top = top + "px";
        //按照百分比得到当前滑动的距离
        _this.caption = "当前滑块的移动的百分比：" + parseInt(top/(scroll.offsetHeight - bar.offsetHeight) * 100) + "%";
        //防止选择内容
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
      }
    }
    //当鼠标弹起的时候，不做任何操作
    document.onmouseup = function() {
      document.onmousemove = null;
    }
  }
}
</script>
<style lang="less">
* {
  margin: 0;
  padding: 0;
}
.scroll{
  margin-left: 5px;
  margin-top: 10px;
  //margin: 100px;
  width: 5px;
  height: 200px;
  background: #ccc;
  position: relative;
}

.bar {
  width: 15px;
  height: 10px;
  background: #369;
  position: absolute;
  top: 0px;
  left: -5px;
  cursor: pointer;
}
p{
  margin-left: 100px;
}
</style>
